
import { login, getUserInfo, getUserId } from '@/api/user'
import { resetRouter } from '@/router'
const state = {
  token: localStorage.getItem('myToken') || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    state.token = data
    localStorage.setItem('myToken', data)
  },
  // 退出登录，清空token
  removeToken(state) {
    state.token = ''
    localStorage.removeItem('myToken')
  },
  // 保存用户信息
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 退出登录，清空用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录发送请求获取token
  async login(store, data) {
    const res = await login(data)
    // console.log(res)
    store.commit('setToken', res)
    localStorage.setItem('loginTime', Date.now())
  },
  // 发送请求获取用户信息
  async getUserInfo(store) {
    const res = await getUserInfo()
    const data = await getUserId(res.userId)
    store.commit('setUserInfo', { ...res, ...data })
  },
  // 退出登录，清空数据
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
